import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import roc_curve, roc_auc_score, accuracy_score, classification_report
from sklearn.ensemble import RandomForestClassifier
import matplotlib.pyplot as plt
import joblib
import matplotlib.ticker as mick
# from utils.log import Logger
import warnings
warnings.filterwarnings('ignore')

# logger = Logger("../log/RF_predict.log")

def init(file_path):
    # 读取数据
    # logger.info("读取数据")
    df = pd.read_csv(file_path, encoding="utf-8")
    # logger.info("读取数据完毕")
    return df

def feature_extract(df):
    # 删除无关列
    df = df.drop(columns=["EmployeeNumber", "Over18", "StandardHours"])
    # 添加新特征：平均每家公司工作年限
    df["CompanyAvgYears"] = (df["TotalWorkingYears"] // df["NumCompaniesWorked"]) \
                        .replace([float('inf'), -float('inf')], pd.NA) \
                        .fillna(0).astype(int)

    # print(df.info())
    return df

def eda(df):
    pass


def Predict_data(df):
    # logger.info("开始预测数据")
    # 1- 对文件进行热编码处理
    One_hot_df = pd.get_dummies(df)

    # 2- 处理数据
    x = One_hot_df.drop(["Attrition"],axis=1)
    y = One_hot_df["Attrition"]

    # 3- 标准化处理
    transformer = joblib.load("../model/RF_transformer.pkl")
    x = transformer.transform(x)

    # 4- 使用加载好的模型预测
    estimator = joblib.load("../model/RF_model.pkl")
    y_predict = estimator.predict(x)

    y_predict_proba = estimator.predict_proba(x)
    # logger.info(f"精确率： {accuracy_score(y, y_predict)}")
    # logger.info(f"AUC面积, {roc_auc_score(y, y_predict_proba[:, 1])}")
    print("准确率：", accuracy_score(y, y_predict))
    print(f"AUC面积：{roc_auc_score(y, y_predict_proba[:, 1])}")
    return y_predict


def show_result(y_predict, init_df):
    # 创建画布
    fig = plt.figure(figsize=(40, 20), dpi=150)
    ax = fig.add_subplot()

    # 绘制预测和真实的曲线
    ax.plot(init_df["MonthlyIncome"], y_predict, label="预测结果")  # 预测
    ax.plot(init_df["MonthlyIncome"], init_df["Attrition"], label="真实结果")  # 真实

    # x轴刻度尺美化
    # 横坐标时间若不处理太过密集，这里调大时间展示的间隔
    ax.xaxis.set_major_locator(mick.MultipleLocator(50))
    # 时间展示时旋转45度
    plt.xticks(rotation=45)

    # 其他属性设置
    plt.title("预测结果展示")
    plt.legend()
    plt.savefig("../model/predict")
    plt.show()


if __name__ == '__main__':
    df = init("../data/test2.csv")
    df = feature_extract(df)
    y_predict = Predict_data(df)
    # show_result(y_predict, df)
